package com.leyou.redis.MyJob;

import com.aliyun.oss.model.OSSObjectSummary;
import com.leyou.common.utils.AliyunUtils;
import com.leyou.redis.client.UserClient;
import com.leyou.redis.constant.RedisConstant;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@JobHandler(value = "heima.brand.clean.img.job") //  web配置JobHandler的名称
@Component
public class MyJob extends IJobHandler {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserClient userClient;


    /**
     * 但是spring的@Scheduled只支持6位，年份是不支持的，带年份的7位格式会报错：
     * Cron expression must consist of 6 fields (found 7 in "1/5 * * * * ? 2018")
     * 通过cron表达式 来配置 该方法的执行周期
     * **/

        @Override
        public ReturnT<String> execute(String s) throws Exception {

            List<OSSObjectSummary> ossList = AliyunUtils.getOssList();
            List<String> brands = userClient.getBrands();

            redisTemplate.opsForSet().add(RedisConstant.PIC_DB_RESOURCES, brands);
            redisTemplate.opsForSet().add(RedisConstant.PIC_RESOURCES, ossList);

            Set<String> sdiff = redisTemplate.opsForSet().difference(RedisConstant.PIC_RESOURCES, RedisConstant.PIC_DB_RESOURCES);
        if(sdiff.size()>0){
            for (String filename : sdiff) {
                AliyunUtils.deleteFile(filename); //  删除阿里云上的多余图片
            }
            redisTemplate.delete(RedisConstant.PIC_RESOURCES);  //  删除 redis上的两个集合
            redisTemplate.delete(RedisConstant.PIC_DB_RESOURCES);
            System.out.println("-setmeal--is-scanning---one-more");
        }
        System.out.println("-xxl-job--is-running----");
       return SUCCESS;
    }

}
